<template>
  <div class="board">
    <h4>{{ isWhite ? "白棋执棋" : "黑棋执棋" }}</h4>
    <canvas
      :width="width"
      :height="height"
      class="board__table"
      @click="pressChess"
      id="myCanvas"
    ></canvas>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch, reactive } from "vue";
import { getMatrix } from "@/utils/index";

export default defineComponent({
  name: "Board",
  props: {
    order: {
      type: Number,
      default: 5,
    },
    width: {
      type: Number,
      default: 600,
    },
    height: {
      type: Number,
      default: 600,
    },
  },
  setup(props) {
    let canvasCtx: CanvasRenderingContext2D
    let isWhite = ref(true)
    let tableList: number[][] = reactive([])
    let chessSize = 10
    const drawChess = (x: number, y: number) => {
      canvasCtx.fillStyle = isWhite.value ? "#fafaf8" : "#4d5562"
      // canvasCtx.fillRect(x, y, 10, 10)
      canvasCtx.beginPath()
      canvasCtx.arc(x, y, chessSize, 0, 2 * Math.PI)
      canvasCtx.closePath()
      canvasCtx.fill()
    }
    // 合成一个矩阵，
    const init = () => {
      tableList = getMatrix(props.order - 1, props.order - 1);
      console.log(tableList)
      const myCanvas: HTMLCanvasElement = document.getElementById(
        "myCanvas"
      ) as HTMLCanvasElement
      canvasCtx = myCanvas.getContext("2d") as CanvasRenderingContext2D
      let x, y, top:number, left:number, right:number, bottom:number
      top = left = chessSize + 0.5
      right = props.width - 2 * (chessSize + 0.5)
      bottom = props.height - 2 * (chessSize + 0.5)
      canvasCtx.fillStyle = "#f8e8b5"
      canvasCtx.fillRect(0, 0, props.width, props.height);
      canvasCtx.strokeStyle = "#b5a375"
      tableList.forEach((_, m) => {
        canvasCtx.beginPath();
        canvasCtx.lineWidth = 1
        x = 0;
        y = top + m * (bottom / (tableList.length - 1))
        canvasCtx.moveTo(x, y)
        x = props.width
        canvasCtx.lineTo(x, y)
        x = left + m * (right / (tableList.length - 1))
        y = 0;
        canvasCtx.moveTo(x, y)
        y = props.height
        canvasCtx.lineTo(x, y)
        canvasCtx.closePath()
        canvasCtx.stroke()
      })
    }

    const getStr = () => {
      return "天下如棋 一步三算"
    }

    const pressChess = (ev: MouseEvent) => {
      drawChess(ev.offsetX, ev.offsetY)
      isWhite.value = !isWhite.value
      tableList[0][0] = 1
      console.log(tableList)
    }

    onMounted(init)
    watch(
      tableList,
      (arr: Array<Array<number>>, oldArr: Array<Array<number>>) => {
        console.log(arr)
        console.log('22',oldArr)
      }
    )
    return { drawChess, getStr, pressChess, isWhite }
  },
});
</script>

<style lang="scss">
.board {
  &__table {
    margin: 10px auto;
  }
}
</style>
